#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <cstdlib>
#include "Usage.hpp"
#include "Comm.hpp"
#include "Log.hpp"

const static int max_reconnet_time = 5;

bool VisitServer(std::string &serverip, uint16_t &serverport, int* cnt)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    server.sin_port = htons(serverport);
    int n = connect(sockfd, CONV(&server), sizeof(server));
    if (n < 0)
    {
        std::cerr << "connect error!" << std::endl;
        return false;
    }
    lg.LogMessage(Debug, "connect success, sockfd is %d\n", sockfd);
    *cnt = 0;
    char outbuffer[1024];
    ssize_t m = read(sockfd, outbuffer, sizeof(outbuffer) - 1);
    if (m > 0)
    {
        outbuffer[m] = 0;
        std::cout << "MENU" << std::endl
                  << outbuffer << std::endl
                  << "Please chooose# ";
        memset(&outbuffer, 0, sizeof(outbuffer));
        std::string inbuffer;
        std::getline(std::cin, inbuffer);
        // 并且把选择传给服务端
        write(sockfd, inbuffer.c_str(), inbuffer.size());
        std::cout << "Enter# ";
        inbuffer.clear();
        std::getline(std::cin, inbuffer);
        if (inbuffer == "quit")
            return true;
        m = write(sockfd, inbuffer.c_str(), inbuffer.size());
        if (m > 0)
        {
            n = read(sockfd, &outbuffer, sizeof(outbuffer) - 1);
            std::cout << "Get -> " << outbuffer << std::endl;
            return true;
        }
        else
        {
            WriteErrorMethod(m);
            return false;
        }
    }
    else
    {
        WriteErrorMethod(m);
        return false;
    }
}

// ./tcp_server serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0], argv[1]);
        return 1;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    int count = 0;
    while (count < max_reconnet_time)
    {
        bool result = VisitServer(serverip, serverport, &count);
        if (!result)
        {
            count++;
            lg.LogMessage(Info, "Reconnecting, please wait...\n");
        }
    }
    if (count >= 5)
        std::cout << "server quit" << std::endl;
    else
        std::cout << "client quit" << std::endl;
    return 0;
}